package vip.youngboy.freejump.persist.bus.bustable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import vip.youngboy.freejump.db.DBHelper;
import vip.youngboy.freejump.db.TableOperator;
import vip.youngboy.freejump.db.model.DBTable;
import vip.youngboy.freejump.domain.bus.BusColumn;
import vip.youngboy.freejump.domain.bus.BusTable;
import vip.youngboy.freejump.persist.bus.buscol.BusColPersistence;
import vip.youngboy.freejump.persist.bus.bustable.BusTablePersistence;
import vip.youngboy.freejump.repository.BusTableRepository;

import java.util.Iterator;
import java.util.List;

@Component
public class DefaultBusTablePersistence implements BusTablePersistence {

    @Autowired
    private BusTableRepository busTableRepository;

    @Autowired
    private BusColPersistence busColPersistence;

    @Autowired
    private DBHelper dbHelper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(BusTable busTable) {

        //校验参数
        busTableRepository.save(busTable);
        //保存列
        if (StringUtils.isEmpty(busTable.getId())) {
            //新对象

        } else {
            //更改列
            //删除列数据
        }

        //判断是否需要生成表

    }

    @Override
    public BusTable getByKey(String key) {
        return busTableRepository.findByKey(key);
    }

    @Override
    public BusTable getFilledByKey(String key) {
        //TODO 添加缓存
        //填充字段相关属性
        BusTable busTable = getByKey(key);


        return null;
    }

    private void fill(BusTable busTable) {
        if (busTable != null) {
            List<BusColumn> columns = this.busColPersistence.getByTableId(busTable.getId());
            for (BusColumn column : columns) {
                column.setBusTable(busTable);
            }
            busTable.setBusColumns(columns);
            TableOperator tableOperator = this.newTableOperator(busTable);
            busTable.setIsCreate(tableOperator.isTableCreated());
        }
    }


    @Override
    public TableOperator newTableOperator(BusTable busTable) {
        DBTable dbTable = busTable.toTable();
        TableOperator tableOperator = dbHelper.createTableOperator(dbTable, jdbcTemplate);
        return tableOperator;
    }

    @Override
    public TableOperator newTableOperatorCheckExist(BusTable busTable) {
        TableOperator tableOperator = newTableOperator(busTable);
        boolean isCreate = tableOperator.isTableCreated();
        if (!isCreate) {
            throw new RuntimeException("表" + busTable.getName() + "不存在");
        }
        return tableOperator;
    }

}
